package com.example.administrator.bleapp;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.bleapp.beanEvent.CallbackDataEvent;
import com.example.administrator.bleapp.beanEvent.ConnectEvent;
import com.example.administrator.bleapp.beanEvent.NotifyDataEvent;
import com.example.administrator.bleapp.common.BluetoothDeviceManager;
import com.vise.baseble.common.PropertyType;
import com.vise.baseble.model.BluetoothLeDevice;
import com.vise.baseble.utils.HexUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class DeviceControlActivity extends AppCompatActivity {

    private BluetoothLeDevice bean;

    TextView tvState;

    public static void start(Activity context, BluetoothLeDevice bean) {
        Intent starter = new Intent(context, DeviceControlActivity.class);
        starter.putExtra("bean",bean);
        context.startActivity(starter);
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_control);
        bean = getIntent().getParcelableExtra("bean");
        tvState = findViewById(R.id.tv_state);
    }

    /**
     * 连接设备
     */
    private void concatenon() {
        if (!BluetoothDeviceManager.getInstance().isConnected(bean)) {
            BluetoothDeviceManager.getInstance().connect(bean);
        }
    }

    /**
     * 断开设备
     */
    private void disconnect() {
        if (BluetoothDeviceManager.getInstance().isConnected(bean)) {
            BluetoothDeviceManager.getInstance().disconnect(bean);
        }
    }

    //连接通知
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showConnectedDevice(ConnectEvent event) {
        if (event != null) {
            if (event.isSuccess()) {
                //连接成功
            }
        }else {
            if (event.isDisconnected()) {
                //连接断开
            }else {
                //连接失败
            }
        }
    }

    /**
     * 数据回调
     * @param event
     */
    @Subscribe
    public void showDeviceCallbackData(CallbackDataEvent event) {
        if (event != null) {
            if (event.isSuccess()) {
                if (event.getBluetoothGattChannel() != null && event.getBluetoothGattChannel().getCharacteristic() != null
                        && event.getBluetoothGattChannel().getPropertyType() == PropertyType.PROPERTY_READ) {
                    String Uuid = event.getBluetoothGattChannel().getCharacteristic().getUuid().toString();
                    byte[] data = event.getData();
                }
            }
        }

    }

    //返回数据
    @Subscribe
    public void showDeviceNotifyData(NotifyDataEvent event) {
        if (event != null && event.getData() != null && event.getBluetoothLeDevice() != null
                && event.getBluetoothLeDevice().getAddress().equals(bean.getAddress())) {
            String data = HexUtil.encodeHexStr(event.getData()); //输出数据

            tvState.append(data+"\n");
        }
    }

    private void sendMessage(String message) {
        if (!isHexData(message)) {
            Toast.makeText(this, "请输入16进制", Toast.LENGTH_SHORT).show();
            return;
        }
        BluetoothDeviceManager.getInstance().write(bean,HexUtil.decodeHex(message.toCharArray()));
    }



    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    private boolean isHexData(String str) {
        if (str == null) {
            return false;
        }
        char[] chars = str.toCharArray();
        if ((chars.length & 1) != 0) {//个数为奇数，直接返回false
            return false;
        }
        for (char ch : chars) {
            if (ch >= '0' && ch <= '9') continue;
            if (ch >= 'A' && ch <= 'F') continue;
            if (ch >= 'a' && ch <= 'f') continue;
            return false;
        }
        return true;
    }
}
